<template>
	<view class="central">
		<view class="central-box">
			<view class="central-box-title ff-color-222 ff-font-25 ff-font-weight-600">请选择服务类型</view>
			<!-- 用户类型(1:救援机构人员 5:单位用户 8:维保人员 9: 维保专家 10:技术人员) -->
			<!-- 单位入口 -->
			<view v-if="userInfo.userType == 5">
				<view class="central-box-details ff-align-items-one ff-flex-between"
					:class="{ 'box-bottom': !jurisdictionList.maintenance.msg }">
					<view class="ff-align-items">
						<image class="ff-margin-right-20 maintenance-logo animate__animated animate__rubberBand"
							src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/central-maintenance-logo.png"
							mode=""></image>
						<view class="ff-font-18">维保业务</view>
					</view>
					<view class="central-box-details-go ff-font-15"><u-button type="primary" @click="maintenanceClick"
							shape="circle">前往</u-button></view>
				</view>
				<view class="central-box-details ff-align-items-one ff-flex-between"
					:class="{ 'box-bottom': !jurisdictionList.assess.msg }">
					<view class="ff-align-items">
						<image class="ff-margin-right-20 assessment-logo animate__animated animate__bounce"
							src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/central-assessment-logo.png"
							mode=""></image>
						<view class="ff-font-18">评估业务</view>
					</view>
					<view class="central-box-details-go ff-font-15"><u-button type="primary" @click="assessmentClick"
							shape="circle">前往</u-button></view>
				</view>
				<view class="central-box-details ff-align-items-one ff-flex-between"
					:class="{ 'box-bottom': !jurisdictionList.maintenance.msg }">
					<view class="ff-align-items">
						<image class="ff-margin-right-20 detection-logo detection animate__animated animate__bounceIn"
							src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/central-detection-logo.png"
							mode=""></image>
						<view class="ff-font-18">检测业务</view>
					</view>
					<view class="central-box-details-go ff-font-15"><u-button type="primary" @click="detectionClick"
							shape="circle">前往</u-button></view>
				</view>
			</view>

			<!-- 机构入口 -->
			<view v-if="userInfo.userType == 8">
				<view>
					<view class="central-box-details ff-align-items-one ff-flex-between"
						:class="{ 'box-bottom': !jurisdictionList.maintenance.msg }">
						<view class="ff-align-items">
							<image class="ff-margin-right-20 maintenance-logo animate__animated animate__rubberBand"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/central-maintenance-logo.png"
								mode=""></image>
							<view class="ff-font-18">维保业务</view>
						</view>
						<view class="central-box-details-go ff-font-15">
							<u-button type="primary" @click="maintenanceClick"
								:disabled="jurisdictionList.maintenance.flag !== 0" shape="circle">前往</u-button>
						</view>
					</view>
					<view class="ff-font-13 ff-text-right" v-if="jurisdictionList.maintenance.msg">
						{{ jurisdictionList.maintenance.msg }}
					</view>
				</view>
				<view>
					<view class="central-box-details ff-align-items-one ff-flex-between"
						:class="{ 'box-bottom': !jurisdictionList.assess.msg }">
						<view class="ff-align-items">
							<image class="ff-margin-right-20 assessment-logo animate__animated animate__bounce"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/central-assessment-logo.png"
								mode=""></image>
							<view class="ff-font-18">评估业务</view>
						</view>
						<view class="central-box-details-go ff-font-15">
							<u-button type="primary" @click="assessmentClick"
								:disabled="jurisdictionList.assess.flag !== 0" shape="circle">前往</u-button>
						</view>
					</view>
					<view class="ff-font-13 ff-text-right" v-if="jurisdictionList.assess.msg">
						{{ jurisdictionList.assess.msg }}
					</view>
				</view>
				<view>
					<view class="central-box-details ff-align-items-one ff-flex-between"
						:class="{ 'box-bottom': !jurisdictionList.maintenance.msg }">
						<view class="ff-align-items">
							<image
								class="ff-margin-right-20 detection-logo detection animate__animated animate__bounceIn"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/central-detection-logo.png"
								mode=""></image>
							<view class="ff-font-18">检测业务</view>
						</view>
						<view class="central-box-details-go ff-font-15">
							<u-button type="primary" @click="detectionClick"
								:disabled="jurisdictionList.maintenance.flag !== 0" shape="circle">前往</u-button>
						</view>
					</view>
					<view class="ff-font-13 ff-text-right" v-if="jurisdictionList.maintenance.msg">
						{{ jurisdictionList.maintenance.msg }}
					</view>
				</view>
			</view>

			<view class="ff-text-center logout"><u-button @click="logout" shape="circle">退出登录</u-button></view>
		</view>
		<!-- 用户授权提示弹框 -->
		<u-modal v-model="authorityModal" title="温馨提示" @confirm="userAuthorityConfirm"
			:content-style="{ 'line-height': '1.5' }" show-cancel-button="true" content="为了更好为您服务，我们需要获取您的微信授权！" />
		<!-- 退出登录 -->
		<u-modal v-model="logoutModal" title="退出账号" @confirm="logoutConfirm" show-cancel-button="true"
			content="请确认是否退出？" />
		<!-- 动画加载框 -->
		<f-loading ref="loading" />
		<!-- 提示框 -->
		<u-toast ref="uToast" />
		<!-- 自定义弹窗 -->
		<f-showModel @setVisible="setVisible" :customShowModal.sync="customShowModal" />
	</view>
</template>

<script>
	import config from '@/tools/config.js'
	import wsRequest from '@/tools/websoket.js'
	import {
		Base64
	} from 'js-base64'
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	export default {
		name: 'central',
		data() {
			return {
				logoutModal: false, // 退出登录弹框
				authorityModal: false, // 授权个人信息弹框显/隐
				jurisdictionList: {}, // 按钮权限返回
				// 自定义弹窗内容
				customShowModal: {
					visible: false, // 显隐
					title: '', // 标题,
					content: '', // 内容,
					cancelText: '', // 取消按钮文案,
					confirmText: '', // 确定按钮文案
					messageType: '', // 到期or未到期
					operatorFlag: null, // 单证/双证
				}
			};
		},
		onLoad() {
			// 判断用户是否开启微信授权
			// let userAuthority = uni.getStorageSync('userAuthority') || false;
			// if (userAuthority == false) {
			// 	this.authorityModal = true; // 调取弹框
			// 	return;
			// }
			// 当机构员工登录的时候调取全局方法（判断是否开启了执业）
			if (uni.getStorageSync('userInfo').userType == 8) {
				getApp().getConfigCenter(); // 获取配置信息以及最新一次维保人员的信息，判断是否开启定时任务
				this.openWebsocket() // websoket启动
			}
			this.getJurisdiction(); // 获取按钮权限
			this.getUserInfo(); // 获取的个人信息
			// this.checkSubscription(); // 用户订阅
		},
		onShow() {
			uni.hideHomeButton(); // 隐藏小房子
		},
		computed: {
			...mapState({
				userInfo: modules => modules.infoList.userInfo, // 获取用户信息
				roleStatus: modules => modules.infoList.roleStatus // 用户角色状态
			})
		},
		methods: {
			...mapMutations(['setUserInfo', 'changeTabberIndex']),
			...mapActions(['tabberAdministrators', 'tabberStaff']),
			// 打开websocket
			openWebsocket() {
				let params = '';
				let encryptionStr = Base64.encode(uni.getStorageSync('token')); // base64转化的token
				console.log(`${config.wsUrl}/orgStaffCertificateWebSocket/${encryptionStr}`)
				this.websocket = new wsRequest(
					`${config.wsUrl}/orgStaffCertificateWebSocket/${encryptionStr}`, 5000, params);
				this.websocket.getMessage(res => {
					console.log('后端返回的数据---', JSON.parse(res.data));
					const datas = JSON.parse(res.data)
					this.closeWebsocket() // 关闭websocket
					this.customShowModal.visible = true // 显隐
					this.customShowModal.messageType = datas.messageType
					this.customShowModal.operatorFlag = datas.operatorFlag
					if (datas.messageType == 1) {
						if (!this.customShowModal.operatorFlag) {
							this.customShowModal.confirmText = '退出账号'
							this.customShowModal.title = '证书已到期' // 标题
							this.customShowModal.content = '您的注册消防工程师证书已到期，无法进行操作，即将退出账号。' // 单证书
						} else {
							this.customShowModal.confirmText = '好的'
							this.customShowModal.title = '证书已到期' // 标题
							this.customShowModal.content = '您的注册消防工程师证书已到期，无法进行负责人相关的操作。' // 双证书
						}
					} else if (datas.messageType == 2) {
						this.customShowModal.title = '证书即将到期' // 标题
						this.customShowModal.confirmText = '确定'
						this.customShowModal.content =
							`您的注册消防工程师证书还有${datas.timeLimit}天到期，请提前处理分配给您的任务，到期后无法再进行相关操作。` // 内容
					}
				})
			},
			// 关闭websocket
			closeWebsocket() {
				// this.websocket.socketTask.close() // 关闭websocket
				this.websocket.closeWebsocket()
			},
			// 关闭提示弹窗
			setVisible() {
				let that = this
				that.customShowModal.visible = false
				if (!that.customShowModal.operatorFlag) {
					if (that.customShowModal.messageType == 1) {
						that.changeTabberIndex(0); // 底部导航栏Index默认为0
						uni.clearStorageSync(); // 清空本地所有的缓存数据
						setTimeout(() => {
							that.$pageJump.reLaunch('/pages/loginRegister/login/Login');
						}, 500);
					}
				}

			},
			// 用户订阅
			checkSubscription() {
				// 要检查的订阅id
				let id = 'dEoXWZSL0vgvdAANtqZKQq9irJ23Z70bsDhBdT0QSj8'
				let that = this
				uni.getSetting({
					withSubscriptions: true,
					success(res) {
						// console.log('获取系统信息', res)s
						if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
							if (res.subscriptionsSetting.itemSettings) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
								let moIdState = res.subscriptionsSetting.itemSettings[id]; // 用户同意的消息模板id
								if (moIdState === 'accept') {
									console.log('接受了消息推送');
								} else if (moIdState === 'reject') {
									console.log('拒绝了消息推送');
									uni.showModal({
										title: '订阅消息',
										content: '您尚未订阅该消息，是否立即订阅？',
										confirmText: '订阅',
										confirmColor: '#3178FF',
										success: (res) => {
											if (res.confirm) {
												// 用户点击了订阅按钮，调起订阅接口
												uni.requestSubscribeMessage({
													tmplIds: [id],
													success(res) {
														if (res[id] === 'accept') {
															// 用户同意订阅该消息，执行相应操作
															that.getOpenid() // 获取openid
														} else {
															// 用户拒绝订阅该消息，建议提醒用户开启订阅消息
														}
													},
													fail(err) {
														console.log(err)
													}
												})
											} else {
												uni.showModal({
													title: '温馨提示',
													content: '如果您取消订阅，将获取不到最新消息',
													confirmText: '订阅',
													confirmColor: '#3178FF',
													success: (res) => {
														if (res.confirm) {
															// 用户点击了订阅按钮，调起订阅接口
															uni.requestSubscribeMessage({
																tmplIds: [id],
																success(res) {
																	if (res[id] ===
																		'accept') {
																		// 用户同意订阅该消息，执行相应操作
																		that.getOpenid() // 获取openid
																	} else {
																		// 用户拒绝订阅该消息，建议提醒用户开启订阅消息
																	}
																},
																fail(err) {
																	console.log(
																		err)
																}
															})
														}
													}
												})
											}
										}
									})
								} else if (moIdState === 'ban') {
									console.log("已被后台封禁");
								}
							} else {
								console.log('我是一号测试')
								uni.showModal({
									title: '订阅消息',
									content: '您尚未订阅该消息，是否立即订阅？',
									confirmColor: '#3178FF',
									confirmText: '订阅',
									success: (res) => {
										if (res.confirm) {
											// 用户点击了订阅按钮，调起订阅接口
											console.log('我是一号测试1')
											uni.requestSubscribeMessage({
												tmplIds: [id],
												success(res) {
													if (res[id] === 'accept') {
														console.log('我是一号测试2')
														// 用户同意订阅该消息，执行相应操作
														that.getOpenid() // 获取openid
													} else {
														// 用户拒绝订阅该消息，建议提醒用户开启订阅消息
														console.log('我是一号测试3')
													}
												},
												fail(err) {
													console.log(err)
												}
											})
										} else {
											uni.showModal({
												title: '温馨提示',
												content: '如果您取消订阅，将获取不到最新消息',
												confirmText: '订阅',
												confirmColor: '#3178FF',
												success: (res) => {
													if (res.confirm) {
														// 用户点击了订阅按钮，调起订阅接口
														uni.requestSubscribeMessage({
															tmplIds: [id],
															success(res) {
																if (res[id] ===
																	'accept') {
																	// 用户同意订阅该消息，执行相应操作
																	that.getOpenid() // 获取openid
																} else {
																	// 用户拒绝订阅该消息，建议提醒用户开启订阅消息
																}
															},
															fail(err) {
																console.log(err)
															}
														})
													}
												}
											})
										}
									}
								})
							}
						} else {
							uni.openSetting({
								withSubscriptions: true,
							})
						}
					}
				})
			},
			// 获取openid
			getOpenid() {
				let that = this;
				uni.login({
					provider: 'weixin',
					success: res => {
						console.log('登录成功：', res);
						// 获取临时登录凭证code
						that.$http
							.get({
								url: '/getOpenId',
								data: {
									code: res.code
								}
							})
							.then(item => {
								console.log('小程序openid------:', item);
								that.$http
									.post({
										url: `/wxMessage/storeOpenId/?openId=${item.data}`
									}).then(e => {
										console.log('保存openid', e)
									})
							});
					},
					fail: () => {
						console.log('登录失败，获取小程序openid失败------：', err);
					}
				});
			},
			// 用户点击了授权操作
			userAuthorityConfirm() {
				uni.getUserProfile({
					desc: '您即将授权消防维保技术小程序',
					success(res) {
						console.log('用户同意了授权-------', res);
						uni.setStorageSync('userAuthority', res.userInfo);
					},
					fail: () => {
						// console.log('用户拒绝了授权-------', err);
					}
				});
			},
			// 获取的个人信息
			async getUserInfo() {
				this.$refs.loading.openLoading('加载中···'); // 打开loading动画
				const data = await this.$http.get({
					url: '/sys/user/info'
				});
				// console.log('获取的个人信息------', data);
				this.$refs.loading.closeLoading(); // 关闭loading动画
				if (data.code == 200) {
					this.setUserInfo(data.data); // 登录后获取的用户信息
				}
			},
			// 获取用户的维保和评估的权限（单位和机构）
			getJurisdiction() {
				this.$refs.loading.openLoading('加载中···'); // 打开loading动画
				this.$http.get({
					url: '/serviceOrg/serviceType'
				}).then(res => {
					// console.log('获取用户的维保和评估的权限（单位和机构）-------', res);
					this.$refs.loading.closeLoading();
					if (res.code == 200) {
						this.jurisdictionList = res.data;
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error'
						});
					}
				});
			},
			// 跳转-------------维保系列页面
			maintenanceClick() {
				//  用户类型(1:救援机构人员 5:单位 8:维保 9: 维保专家 10:技术人员)
				// 单位业务（无权限限制）
				if (this.userInfo.userType == 5) {
					// 业务跳转
					switch (this.roleStatus) {
						case '0': // 单位管理员
						case 1: // 单位员工
							this.tabberAdministrators(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/maintenance/company/Company');
							break;
						default:
							break;
					}
					return;
				}
				// 机构业务（有权限限制）
				if (this.userInfo.userType == 8 && this.jurisdictionList.maintenance.flag == 0) {
					switch (this.roleStatus) {
						case 2: // 机构管理员
							this.tabberAdministrators(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/maintenance/mechanism/Maintenance');
							break;
						case 3: // 机构员工
							this.tabberStaff(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/maintenance/mechanism/Maintenance');
							break;
						default:
							break;
					}
					return;
				}
			},
			// 跳转----------------评估系列页面
			// 单位业务（无权限限制）
			assessmentClick() {
				if (this.userInfo.userType == 5) {
					// 业务跳转
					switch (this.roleStatus) {
						case '0': // 单位管理员
						case 1: // 单位员工
							this.tabberAdministrators(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/assessment/company/Company');
							break;
						default:
							break;
					}
					return;
				}
				// 机构业务（有权限限制）
				if (this.userInfo.userType == 8 && this.jurisdictionList.assess.flag == 0) {
					switch (this.roleStatus) {
						case 2: // 机构管理员
							this.tabberAdministrators(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/assessment/mechanism/Maintenance');
							break;
						case 3: // 机构员工
							this.tabberStaff(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/assessment/mechanism/Maintenance');
							break;
						default:
							break;
					}
					return;
				}
			},
			// 跳转----------------检测系列页面
			// 单位业务（无权限限制）
			detectionClick() {
				if (this.userInfo.userType == 5) {
					// 业务跳转
					switch (this.roleStatus) {
						case '0': // 单位管理员
						case 1: // 单位员工
							this.tabberAdministrators(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/detection/company/Company');
							break;
						default:
							break;
					}
					return;
				}
				// 机构业务（有权限限制）
				if (this.userInfo.userType == 8 && this.jurisdictionList.maintenance.flag == 0) {
					switch (this.roleStatus) {
						case 2: // 机构管理员
							this.tabberAdministrators(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/detection/mechanism/Maintenance');
							break;
						case 3: // 机构员工
							console.log('this.roleStatus', this.roleStatus)
							this.tabberStaff(); // 给底部导航栏赋值
							this.$pageJump.navigateTo('/pages/detection/mechanism/Maintenance');
							break;
						default:
							break;
					}
					return;
				}
			},
			// 退出登录
			logout() {
				this.logoutModal = true; // 打开退出登录的弹框
			},
			logoutConfirm() {
				let that = this;
				that.$refs.loading.openLoading('退出中···'); // 打开loading动画
				that.$http.post({
					url: '/logout'
				}).then(res => {
					// console.log('退出操作返回的数据-----', res);
					that.$refs.loading.closeLoading();
					if (res.code == 200 && res.success) {
						that.changeTabberIndex(0); // 底部导航栏Index默认为0
						uni.clearStorageSync(); // 清空本地所有的缓存数据
						if (that.userInfo.userType == 8) {
							// getApp().closeScheduledTask(); // 关闭定时任务
							getApp().closeWebsocket(); // 关闭websocket任务
						}
						that.$refs.uToast.show({
							title: '退出成功',
							type: 'success'
						});
						setTimeout(() => {
							that.$pageJump.reLaunch('/pages/loginRegister/login/Login');
						}, 500);
					} else {
						that.$refs.uToast.show({
							title: res.msg,
							type: 'error'
						});
					}
				});
			}
		},
		onShareAppMessage() {
			return {
				title: '分享小程序给朋友',
				path: '/pages/homePage/Home'
			};
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.central-activeDisabled {
		background: #f2f2f2 !important;
		color: #a1a1a1 !important;
	}

	.central {
		width: 100%;
		height: 100%;
		box-sizing: border-box;

		.box-bottom {
			margin-bottom: 60rpx;
		}

		&-box {
			margin: 150rpx 10%;

			&-title {
				margin-bottom: 141rpx;
			}

			&-details {
				padding: 0 40rpx 0 70rpx;
				height: 172rpx;
				line-height: 172rpx;
				background-color: #f5f6fa;
				border-radius: 35rpx;

				.ff-align-items {
					.maintenance-logo {
						width: 48rpx;
						height: 58rpx;
					}

					.assessment-logo {
						width: 54rpx;
						height: 44rpx;
					}

					.detection-logo {
						width: 50rpx;
						height: 58rpx;
					}

					.ff-font-18 {
						color: #1b315e;
					}
				}

				&-go {
					/deep/.u-btn--primary {
						height: 68rpx !important;
						line-height: 68rpx !important;
						padding: 5px 37rpx;
					}
				}
			}

			.ff-font-13 {
				margin: 20rpx 0 48rpx;
				color: #b5bbc8;
			}

			.logout {
				position: fixed;
				bottom: 5%;
				width: 80%;

				/deep/.u-btn--default {
					color: #95979e;
					border-color: #95979e;
					height: 100rpx !important;
					line-height: 100rpx !important;
				}
			}
		}
	}

	//x,xs
	@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
		.logout {
			bottom: 20%;
		}
	}

	// xr
	@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) {
		.logout {
			bottom: 20%;
		}
	}

	// xs max
	@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
		.logout {
			bottom: 20%;
		}
	}
</style>